package com.jiyongjun.component.exception.convertor;

import com.jiyongjun.component.config.LogSwitch;
import com.jiyongjun.component.core.model.CommonResult;
import com.jiyongjun.component.core.model.DubboLogContext;
import com.jiyongjun.component.exception.parser.ExceptionParseResult;
import org.apache.dubbo.rpc.Result;

/**
 * <h2></h2>
 * <h3>描述：</h3>
 *
 * @author yongjun.jyj
 * @since 2022/7/14 19:19
 */
public class DefaultDubboProviderExceptionConvertor implements DubboProviderExceptionConvertor {
    @Override
    public Object converExceptionToReturnTypeInstance(Class<?> returnType, ExceptionParseResult exceptionParseResult) {
        if (CommonResult.class.isAssignableFrom(returnType)) {
            return CommonResult.failed(exceptionParseResult.getMsgCode(), exceptionParseResult.getMsgInfo());
        }
        return null;
    }

    @Override
    public void handleResponse(Result result, DubboLogContext logContext) {
        Object appResponse = result.getValue();
        if (appResponse instanceof CommonResult) {
            CommonResult<?> commonResult = (CommonResult<?>) appResponse;
            if (LogSwitch.BIZ_EXCEPTION_CODES.contains(commonResult.getMsgCode())) {
                logContext.setBizException(commonResult.getMsgCode(), commonResult.getMsgInfo(), null);
            } else {
                logContext.setServiceException(commonResult.getMsgCode(), commonResult.getMsgInfo(), null);
            }
        }
    }

}
